package com.project.webapp.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 上傳圖片實作類
 * @author Sn
 *
 */
public class UpLoadAction extends ActionSupport 
{
	/**
	 * 序列化版本號
	 */
	private static final long serialVersionUID = -7822124178759188199L;
	
	//設置上傳圖片的大小
	private static final int BUFFER_SIZE = 16 * 1024;
	
	//上傳方法
	public void uploadFile() throws IOException 
	{
		boolean upLoadFlag = false;
		
		String filePathStr = (String)ServletActionContext.getRequest().getParameter("uplFiles");
		
		String[] srcFiles = filePathStr.split(",");
		
		String serverPath = ServletActionContext.getServletContext().getRealPath("/") + "upload\\";
		
		//判斷上傳文件夾是否存在，不存在就創建
		if (!(new File(serverPath)).exists() && !(new File(serverPath)).isDirectory()) 
		{
			new File(serverPath).mkdir();
		}
		
		for (int i = 0; i < srcFiles.length; i++) 
		{
			String fileName = srcFiles[i].substring(srcFiles[i].lastIndexOf('\\') + 1);
			//根据服务器的文件保存地址和原文件名创建目录文件全路径
			String dstPath = serverPath + fileName;
			File dstFile = new File(dstPath);
			if (copy(new File(srcFiles[i]), dstFile)) 
			{
				upLoadFlag = true;
				
			}else 
			{
				upLoadFlag = false;
				break;
			}
		}
		
        PrintWriter writer = null;
        writer = ServletActionContext.getResponse().getWriter();
        
        if (upLoadFlag) 
        {
        	 writer.print("Y");
        }else 
        {
        	 writer.print("N");
        }
	}
	
	private static boolean copy(File src, File dst) 
	{
		boolean result = false;
		InputStream in = null;
		OutputStream out = null;
		try 
		{
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) 
			{
				out.write(buffer, 0, len);
			}
			result = true;
		} catch (Exception e) 
		{
			e.printStackTrace();
			result = false;
		} finally 
		{
			if (null != in) 
			{
				try 
				{
					in.close();
				} catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
			if (null != out) 
			{
				try 
				{
					out.close();
				} catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
		}
		return result;
	}

}
